package com.dsx.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author dsx
 * @date 2021/3/30 21:29
 * @since JDK1.8
 */
@Slf4j
@Component
@ConfigurationProperties(prefix = "dsx.jwt")
public class JwtUtils {
    //使用yml配置文件为什么读不到？？？？
    private String secret ="f4e2e52034348f86b67cde581c0f9eb5";
    private long expire=604800L;
    private String header="token";
    /**
     * 生成jwt token,并把userId放到subject上
     */
    public String generateToken(long userId) {
        Date now = new Date();
        Date expireTime = new Date(now.getTime() + expire * 1000);
        return Jwts.builder()
                .setHeaderParam("typ","jwt")
                .setSubject(userId+"")
                .setIssuedAt(now)
                .setExpiration(expireTime)
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
    }

    // 获取jwt的信息
    public Claims getClaimByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            log.debug("validate is token error ", e);
            return null;
        }
    }

    /**
     * token是否过期
     * @return  true：过期
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }
}
